package com.kevin.data.batch.component;

import com.kevin.data.batch.configuration.BizJobListener;
import jakarta.annotation.Resource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.FlowBuilder;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.job.flow.Flow;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * 顺序处理
 */
@Component
public class FlowBatchComponent {

    @Resource
    private JobRepository jobRepository;

    @Resource
    private BizJobListener jobListener;

    @Resource
    private PlatformTransactionManager transactionManager;

    @Bean("flowJob")
    public Job flowJob() {
        return new JobBuilder("flowJob", jobRepository).start(flowStep()).next(flowStep3()).end().listener(jobListener).build();
    }

    private Flow flowStep() {
        return new FlowBuilder<Flow>("flowStep").start(flowStep1()).next(flowStep2()).build();
    }

    private Step flowStep1() {
        return new StepBuilder("flowStep1", jobRepository).tasklet((contribution, chunkContext) -> {
            System.err.println("flowStep1 test......");
            return RepeatStatus.FINISHED;
        }, transactionManager).allowStartIfComplete(true).build();
    }

    private Step flowStep2() {
        return new StepBuilder("flowStep2", jobRepository).tasklet((contribution, chunkContext) -> {
            System.err.println("flowStep2 test......");
            return RepeatStatus.FINISHED;
        }, transactionManager).allowStartIfComplete(true).build();
    }

    private Step flowStep3() {
        return new StepBuilder("flowStep3", jobRepository).tasklet((contribution, chunkContext) -> {
            System.err.println("flowStep3 test......");
            return RepeatStatus.FINISHED;
        }, transactionManager).allowStartIfComplete(true).build();
    }

}
